//
//  WatchVideoViewController.m
//  Rail
//
//  Created by hychen on 2018/3/8.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "WatchVideoViewController.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#include <stdio.h>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <net/if.h>
//#include <map>

#import "hcnetsdk.h"

#import "Preview.h"

#import "CollectionDeviceViewController.h"
#import "VideoDownloadViewController.h"
#import "VideoPhotoViewController.h"
#import "VideoBackSeeViewController.h"
#import "PictureInPictureController.h"
#import "SelectFactoryViewController.h"

#import "MJCSegmentInterface.h"

#import "VideoView.h"
#import "BMCustomButton.h"
#import "InnerBaseScrollView.h"
#import "PlayRateTableViewCell.h"
#import "SplitVideoView.h"

#import "RKDropdownAlert.h"
#import "NSDate+Category_lib.h"
#import "AFNetworkReachabilityManager.h"
#import "MediaTool.h"
#import "FFmpegManager.h"

//#define HkTool [HKObserverTool sharedsharedTool]

#define MAX_VIEW_NUM 4

#define kWatchVideoBtnNormalBgColor Color_RGB(0, 193, 224)
#define kWatchVideoBtnSelectBgColor kWhiteColor
#define kWatchVideoBtnNormalTitleColor kWhiteColor
#define kWatchVideoBtnSelectTitleColor Color_RGB(0, 193, 224)
#define ShowSelectDeviceTip [self showSelectDeviceTip];

WatchVideoViewController *thatClass = nil;

@interface WatchVideoViewController ()<UIScrollViewDelegate,VideoViewDelegate>
{
    BOOL isSmallScreen;
}

@property (nonatomic, strong) PictureInPictureController *pictureNav;

@property (nonatomic, strong) NSMutableArray *rateArray;

@property (nonatomic, strong) SelectVideoDeviceModel *selectDeviceModel;

@property (nonatomic, strong) InnerBaseScrollView *scrollView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *deviceNameLabel;
@property (nonatomic, strong) UILabel *deviceAreaLabel;
@property (nonatomic, strong) UILabel *devicestationLabel;
@property (nonatomic, strong) UILabel *deviceLineLabel;

@property (nonatomic, strong) VideoView *videoView;

@property (nonatomic, strong) RKDropdownAlert *RKAlert;

@property (nonatomic, strong) UIView *btnContainer;
@property (nonatomic, strong) BMCustomButton *backSeeBtn;
@property (nonatomic, strong) BMCustomButton *cameraBtn;
@property (nonatomic, strong) BMCustomButton *downloadBtn;
@property (nonatomic, strong) BMCustomButton *collectBtn;

@property (nonatomic, strong) UIView *splitedMaskView;

@property (nonatomic, strong) VideoBackSeeViewController *backSeeVc;
@property (nonatomic, strong) VideoPhotoViewController *cameraVc;
@property (nonatomic, strong) VideoDownloadViewController *downloadVc;
//@property (nonatomic, strong) CollectionDeviceViewController *collectVc;

@property (nonatomic, assign) BOOL isConnectedDevice;

@property (nonatomic, assign) int currentSelectIndex;

@property (nonatomic, strong) NSMutableDictionary *deviceModelDict;
@property (nonatomic, strong) NSMutableDictionary *deviceInfoDict;
@property (nonatomic, strong) NSMutableDictionary *realPlayIdDict;

//收藏
@property (nonatomic, assign) BOOL isCollecting;
@property (nonatomic, assign) BOOL isDownloading;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, copy) NSString *downloadFilePath;

@property (nonatomic, assign) BOOL showNativeDevice;//显示原生设备
@end

@implementation WatchVideoViewController

void g_fExceptionCallBack(DWORD dwType, LONG lUserID, LONG lHandle, void *pUser)
{
    if (dwType == 32784) {
        [RKDropdownAlert title:@"该设备不支持回看" backgroundColor:kWhiteColor textColor:kBlackColor time:1.5];
    }
    NSLog(@"g_fExceptionCallBack Type[0x%x], UserID[%d], Handle[%d]", dwType, lUserID, lHandle);
}

- (instancetype)initWithSelectDeviceModel:(SelectVideoDeviceModel *)model {
    if (self = [super init]) {
        _selectDeviceModel = model;
        //请求视频详情
        [self loadDeviceVideoDetail];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    self.navigationController.navigationBarHidden = NO;
    if (self.videoView.isSplited) {
        self.videoView.hidden = NO;
    }
    //旋转屏幕通知
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(onDeviceOrientationChange)
//                                                 name:UIDeviceOrientationDidChangeNotification
//                                               object:nil
//     ];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    thatClass = self;
    m_lPlaybackID = -1;
    downloadType = -1;
    
    self.view.backgroundColor = kWhiteColor;
    
    [self setupNav];
    
    [self setupVideoView];

    [self setupBtnContainer];
    
    [self setupScrollView];
    
    [self setupChildController];
    
    [IQKeyboardManager sharedManager].enable = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupNav {
    [self.navigationItem addSimpleTitleView:@"查看监控"];
    
    [self.navigationItem addRightItem:self title:@"选择设备" selector:@selector(clickSelectDevice)];
}

- (void)setupVideoView {
    self.videoView = [VideoView new];
    self.videoView.delegate = self;
    self.videoView.backgroundColor = kBlackColor;
    [self.view addSubview:self.videoView];
    self.videoView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kVideoViewH);
}

- (void)setupBtnContainer {
    self.btnContainer = [UIView new];
    [self.view addSubview:self.btnContainer];
    self.btnContainer.frame = CGRectMake(0, CGRectGetMaxY(self.videoView.frame), SCREEN_WIDTH, 65);
    
    //视频回看
    self.backSeeBtn = [BMCustomButton buttonWithType:UIButtonTypeCustom];
    self.backSeeBtn.customStyle = CustomButtonStyleImageTopTitleBottom;
    self.backSeeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.backSeeBtn setTitle:@"视频回看" forState:UIControlStateNormal];
    [self.backSeeBtn setImage:ImageNamed_bb(@"monitoring_video_back_n_ic") forState:UIControlStateNormal];
    [self.backSeeBtn setImage:ImageNamed_bb(@"monitoring_video_back_p_ic") forState:UIControlStateSelected];
    [self.backSeeBtn setTitleColor:kWatchVideoBtnNormalTitleColor forState:UIControlStateNormal];
    [self.backSeeBtn setTitleColor:kWatchVideoBtnSelectTitleColor forState:UIControlStateSelected];
    [self.backSeeBtn addTarget:self action:@selector(backSeeBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backSeeBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.btnContainer addSubview:self.backSeeBtn];
    
    //巡线抓拍
    self.cameraBtn = [BMCustomButton buttonWithType:UIButtonTypeCustom];
    self.cameraBtn.customStyle = CustomButtonStyleImageTopTitleBottom;
    self.cameraBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.cameraBtn setTitle:@"巡线抓拍" forState:UIControlStateNormal];
    [self.cameraBtn setImage:ImageNamed_bb(@"monitoring_video_photograph_n_ic") forState:UIControlStateNormal];
    [self.cameraBtn setImage:ImageNamed_bb(@"monitoring_video_photograph_p_ic") forState:UIControlStateSelected];
    [self.cameraBtn setTitleColor:kWatchVideoBtnNormalTitleColor forState:UIControlStateNormal];
    [self.cameraBtn setTitleColor:kWatchVideoBtnSelectTitleColor forState:UIControlStateSelected];
    [self.cameraBtn addTarget:self action:@selector(cameraBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.cameraBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.btnContainer addSubview:self.cameraBtn];
    
    //回放下载
    self.downloadBtn = [BMCustomButton buttonWithType:UIButtonTypeCustom];
    self.downloadBtn.customStyle = CustomButtonStyleImageTopTitleBottom;
    self.downloadBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.downloadBtn setTitle:@"录像下载" forState:UIControlStateNormal];
    [self.downloadBtn setImage:ImageNamed_bb(@"monitoring_video_download_n_ic") forState:UIControlStateNormal];
    [self.downloadBtn setImage:ImageNamed_bb(@"monitoring_video_download_p_ic") forState:UIControlStateSelected];
    [self.downloadBtn setTitleColor:kWatchVideoBtnNormalTitleColor forState:UIControlStateNormal];
    [self.downloadBtn setTitleColor:kWatchVideoBtnSelectTitleColor forState:UIControlStateSelected];
    [self.downloadBtn addTarget:self action:@selector(downloadBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.downloadBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.btnContainer addSubview:self.downloadBtn];
    
    //收藏设备
    self.collectBtn = [BMCustomButton buttonWithType:UIButtonTypeCustom];
    self.collectBtn.customStyle = CustomButtonStyleImageTopTitleBottom;
    self.collectBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.collectBtn setTitle:@"收藏设备" forState:UIControlStateNormal];
    [self.collectBtn setImage:ImageNamed_bb(@"monitoring_video_collect_n_ic") forState:UIControlStateNormal];
    [self.collectBtn setImage:ImageNamed_bb(@"monitoring_video_collect_p_ic") forState:UIControlStateSelected];
    [self.collectBtn setTitleColor:kWatchVideoBtnNormalTitleColor forState:UIControlStateNormal];
    [self.collectBtn setTitleColor:kWatchVideoBtnSelectTitleColor forState:UIControlStateSelected];
    [self.collectBtn addTarget:self action:@selector(collectBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.btnContainer addSubview:self.collectBtn];
    
    [self.backSeeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.btnContainer);
    }];
    
    [self.cameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.backSeeBtn);
        make.left.equalTo(self.backSeeBtn.mas_right);
    }];
    
    [self.downloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.backSeeBtn);
        make.left.equalTo(self.cameraBtn.mas_right);
    }];
    
    [self.collectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.backSeeBtn);
        make.left.equalTo(self.downloadBtn.mas_right);
        make.right.equalTo(self.btnContainer);
    }];
}

- (void)tap {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

- (void)setupScrollView {
    self.scrollView = [[InnerBaseScrollView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.scrollView];
    self.scrollView.delegate = self;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    tap.cancelsTouchesInView = YES;
    [self.scrollView addGestureRecognizer:tap];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.btnContainer.mas_bottom);
    }];
    
    self.titleLabel = [UILabel labelWithText:@"设备信息" textColor:kBlackColor font:[UIFont systemFontOfSize:17]];
    [self.scrollView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(20);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
    
    self.deviceNameLabel = [UILabel labelWithText:@"设备名称：" textColor:Color_RGB(147, 140, 137) font:[UIFont systemFontOfSize:15]];
    [self.scrollView addSubview:self.deviceNameLabel];
    [self.deviceNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(28);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
    
    self.deviceAreaLabel = [UILabel labelWithText:@"所属工区：" textColor:Color_RGB(147, 140, 137) font:[UIFont systemFontOfSize:15]];
    [self.scrollView addSubview:self.deviceAreaLabel];
    [self.deviceAreaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.equalTo(self.deviceNameLabel.mas_bottom).offset(20);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
    
    self.devicestationLabel = [UILabel labelWithText:@"所属站点：" textColor:Color_RGB(147, 140, 137) font:[UIFont systemFontOfSize:15]];
    [self.scrollView addSubview:self.devicestationLabel];
    [self.devicestationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.equalTo(self.deviceAreaLabel.mas_bottom).offset(20);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
    
    self.deviceLineLabel = [UILabel labelWithText:@"所属线路：" textColor:Color_RGB(147, 140, 137) font:[UIFont systemFontOfSize:15]];
    [self.scrollView addSubview:self.deviceLineLabel];
    [self.deviceLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.top.equalTo(self.devicestationLabel.mas_bottom).offset(20);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];

    if (self.selectDeviceModel) {
        [self setupDeviceInfoWithModel:self.selectDeviceModel];
    }

    _isConnectedDevice = NO;
}

- (void)setupChildController {
    BMWeakSelf
    VideoBackSeeViewController *firstVc = [VideoBackSeeViewController new];
    self.backSeeVc = firstVc;
    [firstVc setBlockClickSeeBack:^(NSDate *backSeeDate) {
        [weakSelf startHKPlayback:weakSelf.currentSelectIndex backSeeDate:backSeeDate];
    }];
    
    VideoPhotoViewController *secondVc = [VideoPhotoViewController new];
    secondVc.watchVc = self;
    self.cameraVc = secondVc;
    [secondVc setBlockUploadLinePhotoSuccess:^{
        [weakSelf handleCaptureLinePhotoSuccess];
    }];
    [secondVc setBlockUploadWarnPhotoSuccess:^{
        [weakSelf handleCaptureWarnPhotoSuccess];
    }];
    [secondVc setBlockUploadWarnVideoSuccess:^(NSDate *fromDate, NSDate *toDate) {
        [weakSelf handleCaptureWarnVideoWithFromDate:fromDate toDate:toDate];
    }];
    [secondVc setBlockCapturePhoto:^{
        [weakSelf handleCapturePhoto];
    }];
    
    VideoDownloadViewController *thirdVc = [VideoDownloadViewController new];
    thirdVc.watchVc = self;
    self.downloadVc = thirdVc;
    
    [thirdVc setBlockClickDownload:^(NSDate *fromDate, NSDate *toDate) {
        if (weakSelf.isDownloading) {
            Show_Msg_Error(@"当前已存在下载任务，请稍后再试")
            return;
        }
        
        [weakSelf downloadVideoFromTime:fromDate toTime:toDate fromType:0];
    }];
    
    [self addChildViewController:firstVc];
    [self addChildViewController:secondVc];
    [self addChildViewController:thirdVc];
    
    [self.view addSubview:firstVc.view];
    firstVc.view.hidden = YES;
    [self.view addSubview:secondVc.view];
    secondVc.view.hidden = YES;
    [self.view addSubview:thirdVc.view];
    thirdVc.view.hidden = YES;
    
    [firstVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.btnContainer.mas_bottom);
    }];
    
    [secondVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.btnContainer.mas_bottom);
    }];
    
    [thirdVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.btnContainer.mas_bottom);
    }];
}

#pragma mark - 设备详情
- (void)loadDeviceVideoDetail {
    BMWeakSelf
    [HttpRequest loadDeviceVideoDetailDataWithDeviceId:self.selectDeviceModel.deviceid success:^(SelectVideoDeviceModel *object) {
        weakSelf.selectDeviceModel = object;
        if ([object isKindOfClass:[SelectVideoDeviceModel class]]) {
            [weakSelf setupDeviceInfoWithModel:object];
            [weakSelf.deviceModelDict setObject:object forKey:@(0)];
            [weakSelf processSelectDeviceCallBack:_selectDeviceModel isSplited:NO];
        }
    } failure:^(NSString *code, NSString *msg) {
        
    }];
}

#pragma mark - 海康
- (void)loginSDK:(int)index {
    BMWeakSelf
    BOOL canStart = [BMUtils checkOpen4gPlayVideoWithCompletion:^{
        [weakSelf _loginSDK:index];
    }];
    
    if (!canStart) {
        return;
    }
    [weakSelf _loginSDK:index];
}

- (void)_loginSDK:(int)index {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
    
    if (model.type == VideoDeviceIPAddressTypeIn) {
        HKVideoUrl = model.in_ipaddress;
        HKVideoAccount = model.auth_user;
        HKVideoPassword = model.auth_pwd;
        HKVideoPort = model.port;
    }
    else if (model.type == VideoDeviceIPAddressTypeOut) {
        HKVideoUrl = model.out_ipaddress;
        HKVideoAccount = model.auth_user;
        HKVideoPassword = model.auth_pwd;
        HKVideoPort = model.map_port;
    }
    else {
        Show_SV_Error_Msg(@"播放出错")
        return;
    }
    
    if (model.userId == -1) {
        BOOL bInit = NET_DVR_Init();
        if (!bInit) {
            if (self.videoView.isSplited) {
                [RKDropdownAlert rotate_title:@"监控连接失败" message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:2];
            }
            else {
                [RKDropdownAlert title:@"监控连接失败" backgroundColor:kWhiteColor textColor:kBlackColor time:2];
            }
            
            return;
        }
        NET_DVR_SetExceptionCallBack_V30(0, NULL, g_fExceptionCallBack, NULL);
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        const char* pDir = [documentPath UTF8String];
        NET_DVR_SetLogToFile(3, (char*)pDir, true);

        //重连设置
//        [self setReconnectPlaySetting];
        
        if ([self loginNormalDevice:index]) {
        }
        else {
            [self showHKErrorMsg];
        }
    }
    else {
        [self loginNormalDevice:index];
    }
}

- (void)logoutSDK:(int)index {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
    NET_DVR_Logout(model.userId);
    NET_DVR_Cleanup();
    model.userId = -1;
}

- (BOOL)loginNormalDevice:(int)index {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
#ifdef DEBUG
    if (self.showNativeDevice) {
        HKVideoUrl = @"218.3.18.26";
        HKVideoAccount = @"admin";
        HKVideoPassword = @"a8888888";
        HKVideoPort = @"6730";
    }
#endif
    
    //  Get value
    NSString * iP = HKVideoUrl;
    NSString * port = HKVideoPort;
    NSString * usrName = HKVideoAccount;
    NSString * password = HKVideoPassword;

    // device login
    NET_DVR_DEVICEINFO_V30 logindeviceInfo = {0};

    // encode type
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    model.userId = NET_DVR_Login_V30((char*)[iP UTF8String],
                                   [port integerValue],
                                   (char*)[usrName cStringUsingEncoding:enc],
                                   (char*)[password UTF8String],
                                   &logindeviceInfo);

    // login on failed
    if (model.userId == -1) {
        return NO;
    }
    
    
    if (self.showNativeDevice) {
        //起始通道号 和 通道数量
        if (logindeviceInfo.byChanNum > 0) {//设备模拟通道个数大于0
            model.startChan = logindeviceInfo.byStartChan;
            model.chanNum = logindeviceInfo.byChanNum;
        }
        //byIPChanNum - 最大数字通道大于0
        else if(logindeviceInfo.byIPChanNum > 0) {
            model.startChan = logindeviceInfo.byStartDChan;
            model.chanNum = logindeviceInfo.byIPChanNum + logindeviceInfo.byHighDChanNum * 256;
        }
    }


    //存储信息
    NSValue *infoValue = [NSValue valueWithBytes:&logindeviceInfo objCType:@encode(NET_DVR_DEVICEINFO_V30)];

    [self.deviceInfoDict setObject:infoValue forKey:@(self.currentSelectIndex)];
    
    VideoPlayView *playView = [self.videoView videoPlayViewWithIndex:index];
    if ([playView isKindOfClass:[VideoPlayView class]]) {
        playView.model = model;
    }
    
    [self startHKPlay:index];
    
    return YES;
}

- (void)releaseHKPlay {
    for (int i = 0; i < self.videoView.playViewArray.count; ++i) {
        int realPlayId = [[self.realPlayIdDict objectForKey:@(i)] intValue];
        
        if (realPlayId != -1) {
            NET_DVR_StopRealPlay(realPlayId);
            [self logoutSDK:i];
            realPlayId = -1;
        }
    }
    
    if(m_lPlaybackID != -1)
    {
        NET_DVR_StopPlayBack(m_lPlaybackID);
        m_lPlaybackID = -1;
    }
    
    NSArray *deviceModelArray = [self.deviceModelDict allValues];
    for (SelectVideoDeviceModel *model in deviceModelArray) {
        if ([model isKindOfClass:[SelectVideoDeviceModel class]]) {
            if(model.userId != -1) {
                NET_DVR_Logout(model.userId);
                model.userId = -1;
            }
        }
    }
    
    NET_DVR_Cleanup();
}

- (void)setReconnectPlaySetting {
    //重连间隔毫秒,1重连
    if (NET_DVR_SetReconnect(5000,1)) {
        NSLog(@"重连设置成功");
    }
    else {
        NSLog(@"重连设置失败:%u",NET_DVR_GetLastError());
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark - 海康开始播放
- (void)startHKPlay:(int)index chanNum:(int)chanNum streamType:(int)streamType {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
    if (!model) {
        NSAssert(1==2, @"播放对应的index模型不存在");
        return;
    }
    
    VideoPlayView *playView = [self.videoView videoPlayViewWithIndex:index];
    
    if (!playView) {
        return;
    }
    
    m_lPlaybackID = -1;
    
    if (model.chanNum > 1) {
        //多频道
        int realPlayId = startPreview(model.userId, chanNum, playView.playContainer, 0, streamType);
        [self.realPlayIdDict setObject:@(realPlayId) forKey:@(index)];
        if (realPlayId < 0) {
            //修改状态
            [self.videoView setPlayStatus:PlayVideoStatusUnknown withIndex:index];
        }
        else {
            //修改状态
            [self.videoView setPlayStatus:PlayVideoStatusPlaying withIndex:index];
//            [self showHKErrorMsg];
            //添加视频预览成功记录
            [self addWatchVideoSuccessHistory];
        }
        
    }
    else {
        //单频道
        int realPlayId = startPreview(model.userId, chanNum, playView.playContainer, 0, streamType);
        [self.realPlayIdDict setObject:@(realPlayId) forKey:@(index)];
        if (realPlayId < 0) {
            //修改状态
            [self.videoView setPlayStatus:PlayVideoStatusUnknown withIndex:index];
        }
        else {
            //修改状态
            [self.videoView setPlayStatus:PlayVideoStatusPlaying withIndex:index];
//            [self showHKErrorMsg];
            //添加视频预览成功记录
            [self addWatchVideoSuccessHistory];
        }
    }
}

- (void)startHKPlay:(int)index {
    VideoPlayView *playView = [self.videoView videoPlayViewWithIndex:index];
    [self startHKPlay:index chanNum:playView.model.startChan streamType:playView.model.streamType];
}

#pragma mark - 海康停止播放
- (void)stopHKPlay:(int)index {
    int realPlayId = [[self.realPlayIdDict objectForKey:@(index)] intValue];
    if (realPlayId != -1) {
        stopPreview(index);
        realPlayId = -1;
        [self.realPlayIdDict setObject:@(realPlayId) forKey:@(index)];
    }
    [self.videoView setPlayStatus:PlayVideoStatusStop withIndex:index];
    [self logoutSDK:index];
}

- (void)stopHKPlayWithNotLogoutSDK:(int)index {
    int realPlayId = [[self.realPlayIdDict objectForKey:@(index)] intValue];
    if (realPlayId != -1) {
        stopPreview(index);
        realPlayId = -1;
        [self.realPlayIdDict setObject:@(realPlayId) forKey:@(index)];
    }
    [self.videoView setPlayStatus:PlayVideoStatusStop withIndex:index];
}

#pragma mark - 海康开始回放
- (void)startHKPlayback:(int)index backSeeDate:(NSDate *)backSeeDate{
    if ([[NSDate date] isEarlierThanDate:backSeeDate]) {
        return;
    }
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
    
    VideoPlayView *playView = [self.videoView videoPlayViewWithIndex:index];
    if (!playView) {
        return;
    }
    
//    [self stopHKPlay:index];
    [self stopHKPlayWithNotLogoutSDK:index];
    
    if(model.userId == -1)
    {
        if (self.videoView.isSplited) {
            [RKDropdownAlert rotate_title:@"监控连接失败" message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:2];
        }
        else {
            [self.RKAlert title:@"视频回看失败" message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:1.5];
        }
        
        NSLog(@"Please login on the device first!");
        return;
    }
    
    NET_DVR_TIME struStartTime = {0};
    NET_DVR_TIME struEndTime = {0};
    
    struStartTime.dwYear = (int)backSeeDate.year;
    struStartTime.dwMonth = (int)backSeeDate.month;
    struStartTime.dwDay = (int)backSeeDate.day;
    struStartTime.dwHour = (int)backSeeDate.hour;
    struStartTime.dwMinute = (int)backSeeDate.minute;
    struStartTime.dwSecond = (int)backSeeDate.seconds;

    struEndTime.dwYear = (int)backSeeDate.year;
    struEndTime.dwMonth = (int)backSeeDate.month;
    struEndTime.dwDay = (int)backSeeDate.day;
    struEndTime.dwHour = (int)backSeeDate.hour+1;
    struEndTime.dwMinute = (int)backSeeDate.minute;
    struEndTime.dwSecond = (int)backSeeDate.seconds;

    m_lPlaybackID = NET_DVR_PlayBackByTime(model.userId, model.startChan, &struStartTime, &struEndTime, (__bridge void*)playView.playContainer);
    
    if (m_lPlaybackID == -1)
    {
        [self showHKErrorMsg];
        [self stopHKPlayback:index];
        return;
    }

    int value = NET_DVR_GetPlayBackPos(m_lPlaybackID);
    NSLog(@"GetPlayBackPos:%d",value);
    
    if (!NET_DVR_PlayBackControl_V40(m_lPlaybackID, NET_DVR_PLAYSTART, NULL, 0, NULL, NULL))
    {
        NSLog(@"NET_DVR_PLAYSTART failed:%d",  NET_DVR_GetLastError());
        [self stopHKPlayback:index];
        return;
    }
    else{
        NSLog(@"NET_DVR_PLAYSTART succ");
        [self.videoView setPlayStatus:PlayVideoStatusPlaying withIndex:index];
        m_bStopPlayback = false;
    }

}

#pragma mark - 海康停止回放
- (void)stopHKPlayback:(int)index {
    if (m_lPlaybackID != -1) {
        NET_DVR_StopPlayBack(m_lPlaybackID);
        m_lPlaybackID = -1;
    }
    [self.videoView setPlayStatus:PlayVideoStatusStop withIndex:index];
}
#pragma mark - 海康抓图
- (void)captureHKPhotoWithSuccess:(void(^)(UIImage *image))success {
    //抓图生成jpg格式
    NET_DVR_SetCapturePictureMode(JPEG_MODE);

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    char szFileName[256] = {0};
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd_hh:mm:ss"];
    NSString* date = [formatter stringFromDate:[NSDate date]];
    sprintf(szFileName, "%s/%s.jpg", (char*)documentsDirectory.UTF8String, (char*)date.UTF8String);

    int realPlayId = [[self.realPlayIdDict objectForKey:@(0)] intValue];
    if (realPlayId > -1) {
        sprintf(szFileName, "%s/%s_pre.jpg", (char*)documentsDirectory.UTF8String, (char*)date.UTF8String);
        //预览抓图
        if (NET_DVR_CapturePictureBlock(realPlayId, szFileName, 0)) {
            NSLog(@"预览抓图 succ[%s]", szFileName);
            UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithUTF8String:szFileName]];
            if (success) {
                success(image);
            }
        }
        else {
            int errorNo = NET_DVR_GetLastError();
            char *errMsg = NET_DVR_GetErrorMsg(&errorNo);
            if (self.videoView.isSplited) {
                [RKDropdownAlert rotate_title:[NSString stringWithFormat:@"抓图失败:%d",errorNo] message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:2];
            }
            else {
                [RKDropdownAlert title:[NSString stringWithFormat:@"抓图失败:%d",errorNo] backgroundColor:kWhiteColor textColor:kBlackColor time:2];
            }
            
            NSLog(@"预览抓图 failed[%s]", errMsg);
        }
    }
    else if (m_lPlaybackID > -1) {
        //回放抓图
        sprintf(szFileName, "%s/%s_back.jpg", (char*)documentsDirectory.UTF8String, (char*)date.UTF8String);
        if(NET_DVR_PlayBackCaptureFile(m_lPlaybackID, szFileName) == -1) {
            NSLog(@"回放抓图 failed[%d]", NET_DVR_GetLastError());
        }
        else {
            NSLog(@"回放抓图 succ[%s]", szFileName);
            NSData *data = [[NSData alloc] initWithContentsOfFile:[NSString stringWithUTF8String:szFileName]];
            UIImage *dataImage = [UIImage imageWithData:data];
            UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithUTF8String:szFileName]];
            if (success) {
                success(image);
            }
        }
    }

}

#pragma mark - 海康静音
- (void)doHKPlayerMuted {
    if (!NET_DVR_CloseSound()) {
        NSLog(@"播放器静音");
    }
}

#pragma mark - 海康恢复声音
- (void)doHKPlayerUnmuted:(int)index {
    int realPlayId = [[self.realPlayIdDict objectForKey:@(index)] intValue];
    if (!NET_DVR_OpenSound(realPlayId)) {
        NSLog(@"播放器恢复声音");
    }
}

#pragma mark - 海康录像下载
- (void)downloadVideoFromTime:(NSDate *)fromDate toTime:(NSDate *)toDate fromType:(int)fromType {
    BMWeakSelf
    BOOL canDownload = [BMUtils checkOpen4gDownloadVideoWithCompletion:^{
        [weakSelf _downloadVideoFromTime:fromDate toTime:toDate fromType:fromType];
    }];
    
    if (!canDownload) {
        Show_SV_Error_Msg(@"下载失败");
        return;
    }
    [weakSelf _downloadVideoFromTime:fromDate toTime:toDate fromType:fromType];
}
- (void)_downloadVideoFromTime:(NSDate *)fromDate toTime:(NSDate *)toDate fromType:(int)fromType {
    
    if (self.isDownloading) {
        return;
    }
    
    if ([fromDate isLaterThanDate:toDate] || [toDate isLaterThanDate:[NSDate date]]) {
        Show_SV_Error_Msg(@"时间选择错误")
        return;
    }
    
//    if (![AFNetworkReachabilityManager sharedManager].isReachableViaWiFi) {
//
//        return;
//    }
    
    self.isDownloading = YES;
    
    //获取当前的播放模型
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(0)];
    
    int userId = model.userId;
    int channelId = model.startChan;
    
    NET_DVR_TIME struStartTime = {0};
    NET_DVR_TIME struEndTime = {0};
    
    struStartTime.dwYear = (int)fromDate.year;
    struStartTime.dwMonth = (int)fromDate.month;
    struStartTime.dwDay = (int)fromDate.day;
    struStartTime.dwHour = (int)fromDate.hour;
    struStartTime.dwMinute = (int)fromDate.minute;
    struStartTime.dwSecond = (int)fromDate.seconds;
    
    struEndTime.dwYear = (int)toDate.year;
    struEndTime.dwMonth = (int)toDate.month;
    struEndTime.dwDay = (int)toDate.day;
    struEndTime.dwHour = (int)toDate.hour;
    struEndTime.dwMinute = (int)toDate.minute;
    struEndTime.dwSecond = (int)toDate.seconds;
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *fileName = [NSString stringWithFormat:@"%ld%02ld%02ld%02ld%02ld%02ld.h264",(long)fromDate.year,(long)fromDate.month,(long)fromDate.day,(long)fromDate.hour,(long)fromDate.minute,(long)fromDate.seconds];
    filePath = [filePath stringByAppendingPathComponent:fileName];
    self.downloadFilePath = filePath;
    int result = NET_DVR_GetFileByTime(userId, channelId, &struStartTime, &struEndTime, (char*)[filePath UTF8String]);

    if (result == -1) {
        [self showHKErrorMsg];
        self.isDownloading = NO;
        downloadType = -1;
    }
    else {
        //开始下载
        bool b = NET_DVR_PlayBackControl_V40(result, NET_DVR_PLAYSTART);
        if (b == true) {
            //成功
            Show_Msg_Success(@"开始下载录像")
            downloadType = fromType;
            [self logDownloadProgress:result];
        }
        else {
            self.isDownloading = NO;
            //失败
            [self showHKErrorMsg];
            downloadType = -1;
        }
    }
}

- (void)logDownloadProgress:(int)downloadId {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(_logDownloadProgress:) userInfo:@{@"downloadId":@(downloadId)} repeats:YES];
    self.timer = timer;
}

- (void)_logDownloadProgress:(NSTimer *)timer {
    if (![[timer.userInfo objectForKey:@"downloadId"] respondsToSelector:@selector(intValue)]) {
        Show_Msg_Error(@"下载失败")
        [self showHKErrorMsg];
        [self.timer invalidate];
        self.timer = nil;
        self.isDownloading = NO;
        downloadType = -1;
        return;
    }
    int downloadId = [[timer.userInfo objectForKey:@"downloadId"] intValue];
    int prgress = NET_DVR_GetDownloadPos(downloadId);
    NSLog(@"当前下载进度:%d",prgress);
    
    if (prgress == 200) {
        Show_Msg_Error(@"下载失败")
        [self showHKErrorMsg];
        [self.timer invalidate];
        self.timer = nil;
        self.isDownloading = NO;
        downloadType = -1;
        return;
    }
    
    if (prgress > 99) {
        [self.timer invalidate];
        self.timer = nil;
        self.isDownloading = NO;
        
        if (downloadType == 1) {
            //上传视频
            NSData *data = [[NSData alloc] initWithContentsOfFile:self.downloadFilePath];
            if ([data isKindOfClass:[NSData class]]) {
                [self.cameraVc _requestWarnVideoData:data];
            }
            else {
                NSLog(@"上传数据出错");
            }
            return;
        }
        BMWeakSelf
        NSString *videoFilePath = [self.downloadFilePath stringByReplacingOccurrencesOfString:@".h264" withString:@".mp4"];
        [[FFmpegManager sharedManager] converWithInputPath:self.downloadFilePath outputPath:videoFilePath processBlock:^(float process) {
            
        } completionBlock:^(NSError *error) {
            //保存到相册
            [MediaTool writeVideoToMUKAssetsGroup:[NSURL URLWithString:videoFilePath] completion:^(int isSuccess) {
                if (isSuccess) {
                    Show_Msg_Success(@"录像保存相册成功")
                }
                
                //移除文件
                if ([[NSFileManager defaultManager] removeItemAtPath:weakSelf.downloadFilePath?:@"" error:NULL]) {
                    NSLog(@"删除下载视频原文件成功:%@",weakSelf.downloadFilePath);
                };
                if ([[NSFileManager defaultManager] removeItemAtPath:videoFilePath error:NULL]) {
                    NSLog(@"删除转码后视频文件成功:%@",videoFilePath);
                };
            }];
        }];
        
    }
}

#pragma mark - 海康获取信息
- (void)getHKConfig:(int)index {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(index)];
    if(model.userId == -1)
    {
        NSLog(@"Please logon a device first!");
        return;
    }

    NET_DVR_COMPRESSIONCFG_V30 struCompress = {0};
    DWORD dwRet = 0;
//    NET_DVR_GET_DEVICECFG_V40 获取设备参数
    if (!NET_DVR_GetDVRConfig(model.userId, NET_DVR_GET_COMPRESSCFG_V30, model.startChan, &struCompress, sizeof(struCompress), &dwRet))
    {
        NSLog(@"NET_DVR_GET_COMPRESSCFG_V30 failed with[%d]", NET_DVR_GetLastError());
    }
    else
    {
        NSLog(@"NET_DVR_GET_COMPRESSCFG_V30 succ");
    }
    //set substream resolution to cif
    struCompress.struNetPara.byResolution = 1;
    if (!NET_DVR_SetDVRConfig(model.userId, NET_DVR_SET_COMPRESSCFG_V30, model.startChan, &struCompress, sizeof(struCompress)))
    {
        NSLog(@"NET_DVR_SET_COMPRESSCFG_V30 failed with[%d]", NET_DVR_GetLastError());
    }
    else
    {
        NSLog(@"NET_DVR_SET_COMPRESSCFG_V30 succ");
    }
}

- (void)showHKErrorMsg {
    int errorNo = NET_DVR_GetLastError();
    char *errMsg = NET_DVR_GetErrorMsg(&errorNo);
    NSLog(@"%@",[NSString stringWithFormat:@"错误代码%d,,,错误信息:%s",errorNo,errMsg]);
    NSString *message = [[NSString alloc] initWithCString:errMsg encoding:NSUTF8StringEncoding];
    
    if (errorNo == 32) {
        message = @"时间输入不正确";
    }
    else if (errorNo == 52) {
        message = @"登陆设备用户数达到最大";
    }
    else if (errorNo == 7) {
        message = @"登录失败";
    }
    else if (errorNo == 9) {
        message = @"从设备接收数据失败";
    }
    else if (errorNo == 10) {
        message = @"从设备接收数据超时";
    }
    else if (errorNo == 65) {
        return;
    }
    else {
        message = @"设备连接失败";
    }
    
    if (self.videoView.isSplited || self.videoView.isFullScreen) {
        return;
    }
    
    if (self.videoView.isSplited) {
        [RKDropdownAlert rotate_title:[NSString stringWithFormat:@"%@:%d",message,errorNo] message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:1.5];
    }
    else {
        [self.RKAlert title:[NSString stringWithFormat:@"%@:%d",message,errorNo] message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:1.5];
    }
    
}

- (void)showSelectDeviceTip {
    [self.RKAlert title:@"请选择设备" message:nil backgroundColor:kWhiteColor textColor:kBlackColor time:1.5];
}

#pragma mark - 添加视频预览成功记录
- (void)addWatchVideoSuccessHistory {
    BMWeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self captureHKPhotoWithSuccess:^(UIImage *image) {
            if (image) {
                [HttpRequest addVideoHistoryDataWithDeviceId:weakSelf.selectDeviceModel.deviceid areaId:weakSelf.selectDeviceModel.areaid image:image success:^(id object) {
                    NSLog(@"添加视频预览成功记录");
                } failure:^(NSString *code, NSString *msg) {
                    NSLog(@"添加视频预览成功失败");
                }];
            }
        }];
    });
}

#pragma mark - 点击事件
- (void)backSeeBtnDidClick:(BMCustomButton *)btn {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
#ifdef DEBUG
//    self.showNativeDevice = YES;
#endif
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(0)];
    
    if (!model) {
        ShowSelectDeviceTip
        return;
    }

    if (model.userId < 0) {
        ShowSelectDeviceTip
        return;
    }
    
    self.cameraVc.showType = showTypeUnknown;
    [self btnResetNormalStatusWithSelectBtn:btn];

    self.backSeeVc.view.hidden = !btn.selected;
    self.cameraVc.view.hidden = YES;
    self.downloadVc.view.hidden = YES;
}

- (void)cameraBtnDidClick:(BMCustomButton *)btn {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(0)];
    if (!model) {
        ShowSelectDeviceTip
        return;
    }
    if (model.userId < 0) {
        ShowSelectDeviceTip
        return;
    }
    
    self.cameraVc.showType = showTypeUnknown;
    if (!self.cameraVc.tableView.hidden) {
        self.cameraVc.tableView.hidden = !self.cameraVc.tableView.hidden;
        return;
    }
    
    [self btnResetNormalStatusWithSelectBtn:btn];
    
    self.backSeeVc.view.hidden = YES;
    self.cameraVc.view.hidden = !btn.selected;
    self.downloadVc.view.hidden = YES;
    
}

- (void)downloadBtnDidClick:(BMCustomButton *)btn {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(0)];
    if (!model) {
        ShowSelectDeviceTip
        return;
    }
    if (model.userId < 0) {
        ShowSelectDeviceTip
        return;
    }
    
    self.cameraVc.showType = showTypeUnknown;
    [self btnResetNormalStatusWithSelectBtn:btn];
    
    self.backSeeVc.view.hidden = YES;
    self.cameraVc.view.hidden = YES;
    self.downloadVc.view.hidden = !btn.selected;
}

- (void)collectBtnDidClick:(BMCustomButton *)btn {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(0)];
    if (!model) {
        ShowSelectDeviceTip
        return;
    }
//    if (model.userId < 0) {
//        ShowSelectDeviceTip
//        return;
//    }
    
    [self btnResetNormalStatusWithSelectBtn:btn];
    [self.collectBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    self.collectBtn.selected = NO;
    
    self.backSeeVc.view.hidden = YES;
    self.cameraVc.view.hidden = YES;
    self.downloadVc.view.hidden = YES;
    
    if ([self.selectDeviceModel.favid respondsToSelector:@selector(integerValue)] && [self.selectDeviceModel.favid integerValue] > 0) {
        [self cancelVideoObserverCollection];
    }
    else {
        [self addVideoObserverCollection];
    }
    
}

- (void)btnResetNormalStatusWithSelectBtn:(BMCustomButton *)selectedBtn {
    BOOL btnSelectStatus = !selectedBtn.selected;
    self.backSeeBtn.selected = NO;
    self.cameraBtn.selected = NO;
    self.downloadBtn.selected = NO;
    self.collectBtn.selected = NO;
    
    [self.backSeeBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.cameraBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.downloadBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.collectBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    
    selectedBtn.selected = btnSelectStatus;
    
    if (selectedBtn.selected) {
        [selectedBtn setBackgroundColor:kWatchVideoBtnSelectBgColor];
    }
}

- (void)resetBtnStatus {
    self.backSeeBtn.selected = NO;
    self.cameraBtn.selected = NO;
    self.downloadBtn.selected = NO;
    self.collectBtn.selected = NO;
    
    [self.backSeeBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.cameraBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.downloadBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    [self.collectBtn setBackgroundColor:kWatchVideoBtnNormalBgColor];
    
    self.backSeeVc.view.hidden = YES;
    self.cameraVc.view.hidden = YES;
    self.downloadVc.view.hidden = YES;
}


- (void)clickSelectDevice {
    SelectFactoryViewController *selectFactory = [SelectFactoryViewController new];
    selectFactory.style = SelectFactoryControllerStyleScanSelectDevice;
    BMWeakSelf
    [selectFactory setBlockSelectDeviceCallBack:^(SelectVideoDeviceModel *deviceModel) {
        weakSelf.selectDeviceModel = deviceModel;
        if (deviceModel) {
            [weakSelf.deviceModelDict setObject:deviceModel forKey:@(weakSelf.currentSelectIndex)];
        }
        [weakSelf processSelectDeviceCallBack:deviceModel isSplited:NO];
    }];
    [self.navigationController pushViewController:selectFactory animated:YES];
}

- (void)selectDeviceButtonDidClick:(UIButton *)btn {
    [self clickSelectDevice];
}

- (void)clicksplitedMaskView {

    [self closePictureInPicture];
}

#pragma mark - 网络
/**
 添加收藏
 */
- (void)addVideoObserverCollection {
    if (self.isCollecting) {
        return;
    }
    self.isCollecting = YES;
    BMWeakSelf
    [HttpRequest addFavWithLineId:@"" areaId:@"" deviceId:self.selectDeviceModel.deviceid?:@"" success:^(id object) {
        weakSelf.isCollecting = NO;
        if ([object isKindOfClass:[NSDictionary class]]) {
            weakSelf.selectDeviceModel.favid = [object objectForKey:@"favid"];
        }
        else if ([object isKindOfClass:[NSNumber class]]) {
            weakSelf.selectDeviceModel.favid = [(NSNumber *)object stringValue];
        }
        else if ([object isKindOfClass:[NSString class]]) {
            weakSelf.selectDeviceModel.favid = object;
        }
        Show_SV_Success_Msg(@"收藏成功")
        [weakSelf.collectBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isCollecting = NO;
        [weakSelf.collectBtn setTitle:@"收藏设备" forState:UIControlStateNormal];
        Show_SV_Msg(msg)
    }];
}

- (void)cancelVideoObserverCollection {
    if ([self.selectDeviceModel.favid respondsToSelector:@selector(integerValue)] && [self.selectDeviceModel.favid integerValue] > 0) {
        if (self.isCollecting) {
            return;
        }
        self.isCollecting = YES;
        BMWeakSelf
        [HttpRequest cancelFavWithFavId:self.selectDeviceModel.favid success:^(id object) {
            weakSelf.isCollecting = NO;
            weakSelf.selectDeviceModel.favid = nil;
            Show_SV_Success_Msg(@"取消成功")
            [weakSelf.collectBtn setTitle:@"收藏设备" forState:UIControlStateNormal];
        } failure:^(NSString *code, NSString *msg) {
            weakSelf.isCollecting = NO;
            [weakSelf.collectBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
            Show_SV_Msg(msg)
        }];
    }
    
}

- (void)addHistoryWatch {
    [HttpRequest addHistoryWatchDataWithAreaId:self.selectDeviceModel.areaid?:@"" deviceId:self.selectDeviceModel.deviceid?:@"" deviceName:self.selectDeviceModel.device_name?:@"" chName:self.selectDeviceModel.ch_name?:@"" success:^(id object) {
        
    } failure:^(NSString *code, NSString *msg) {
        
    }];
}

#pragma mark - 视频抓拍
- (void)handleCaptureLinePhotoSuccess {
    [self resetBtnStatus];
}

- (void)handleCaptureWarnPhotoSuccess {
    [self resetBtnStatus];
}

- (void)handleCaptureWarnVideoWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate {
    [self downloadVideoFromTime:fromDate toTime:toDate fromType:1];
}

- (void)handleCapturePhoto {
    BMWeakSelf
    int realPlayId = [[self.realPlayIdDict objectForKey:@(0)] intValue];
    if (realPlayId < 0 && m_lPlaybackID > -1) {
        //回放抓图 需要调用2次海康的sdk方法，才会成功获取图片数据，不知道为什么。
        [self captureHKPhotoWithSuccess:^(UIImage *image) {
            [weakSelf.cameraVc addCapturePhoto:image];
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self captureHKPhotoWithSuccess:^(UIImage *image) {
                [weakSelf.cameraVc addCapturePhoto:image];
            }];
        });
        
    }
    else {
        [self captureHKPhotoWithSuccess:^(UIImage *image) {
            [weakSelf.cameraVc addCapturePhoto:image];
        }];
    }

}

#pragma mark - 选择设备回调
- (void)processSelectDeviceCallBack:(SelectVideoDeviceModel *)model isSplited:(BOOL)isSpilted{
    
    NSLog(@"选择设备回调:%@",model.device_name);

    
    if (self.videoView.isSplited) {
        self.videoView.hidden = NO;
    }
    
    if (!model) {
        return;
    }
    
    
    if (isSpilted) {
       
    }
    else {
        if ([self.selectDeviceModel.favid respondsToSelector:@selector(integerValue)] && [self.selectDeviceModel.favid integerValue] > 0) {
            [self.collectBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
        }
        else {
            [self.collectBtn setTitle:@"收藏设备" forState:UIControlStateNormal];
        }
        [self stopHKPlay:self.currentSelectIndex];
    }
    

    
    VideoPlayView *playView = [self.videoView videoPlayViewWithIndex:self.currentSelectIndex];
    if ([playView isKindOfClass:[VideoPlayView class]]) {
        playView.model = model;
    }
    
    //添加观看记录
    [self addHistoryWatch];
    
    [self loginSDK:self.currentSelectIndex];
    
    [self setupDeviceInfoWithModel:model];
}

- (void)setupDeviceInfoWithModel:(SelectVideoDeviceModel *)model {
    NSString *deviceName = model.device_name;
    NSString *areaName = model.area_name;
    NSString *stationName = model.station_name;
    NSString *lineName = model.line_name;
    
    self.scrollView.hidden = NO;
    
    self.titleLabel.text = @"设备信息";
    self.deviceNameLabel.text = [NSString stringWithFormat:@"设备名称：%@",deviceName?:@""];
    self.deviceAreaLabel.text = [NSString stringWithFormat:@"所属工区：%@",areaName?:@""];
    self.devicestationLabel.text = [NSString stringWithFormat:@"所属站点：%@",stationName?:@""];
    self.deviceLineLabel.text = [NSString stringWithFormat:@"所属线路：%@",lineName?:@""];
}

#pragma mark - 状态栏
- (BOOL)prefersStatusBarHidden{
    if (self.videoView.isFullScreen) {
        return YES;
    }
    return NO;
}

#pragma mark - 视频
#pragma mark - VideoViewDelegate
//点击了 屏幕中的播放按钮
- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView clickPlayWithIndex:(NSInteger)index count:(NSInteger)count {
    self.currentSelectIndex = (int)index;
    //跳转选择设备
    if (view.isSplited) {
        [self selectDeviceAtPictureInPictureWithIndex:(int)index];
    }
    else {
        [self clickSelectDevice];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView clickVoiceButton:(UIButton *)btn isVoiceMuted:(int)isVoiceMuted {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(playView.index)];
    if (!model) {
        ShowSelectDeviceTip
        return;
    }
    if (model.userId < 0) {
        ShowSelectDeviceTip
        return;
    }
    playView.isVoiceMuted = !playView.isVoiceMuted;
    if (isVoiceMuted) {
        [self doHKPlayerMuted];
    }
    else {
        [self doHKPlayerUnmuted:playView.index];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView clickPlayPauseButton:(UIButton *)btn playStatus:(PlayVideoStatus)status {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(playView.index)];
    if (!model) {
        [self clickSelectDevice];
        return;
    }
//    if (playView.playStatus == PlayVideoStatusUnknown || model.userId < 0) {
//        [self clickSelectDevice];
//    }
    else if (playView.playStatus == PlayVideoStatusPlaying) {
        [self stopHKPlay:playView.index];
    }
    else {
        [self loginSDK:playView.index];
//        [self startHKPlay:playView.index];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView clickFullScreenButton:(UIButton *)btn isFullScreen:(int)isFullScreen {
    SelectVideoDeviceModel *model = [self.deviceModelDict objectForKey:@(playView.index)];
    if (!model) {
        ShowSelectDeviceTip
        return;
    }
    if (model.userId < 0) {
        ShowSelectDeviceTip
        return;
    }
    
    if (isFullScreen) {
        [view toNormalScreenWithSuperView:self.view videoPlayView:playView completion:^(int finished) {
            [self setNeedsStatusBarAppearanceUpdate];
        }];
    }
    else {
        [view toFullScreenWithVideoPlayView:playView completion:^(int finished) {
            [self setNeedsStatusBarAppearanceUpdate];
        }];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView clickSplitScreenButton:(UIButton *)btn isSplitedScreen:(int)isSplitedScreen {
    if (self.videoView.isSplited) {
        //正常模式
        [view cancelSplitedScreen:self.view];
    }
    else {
        //全屏模式
        [view toSplitedScreen];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView videoPlayIndex:(int)index streamTypeSelectWithIndexPath:(NSIndexPath *)indexPath stream:(nonnull VideoStreamModel *)stream ipType:(nonnull VideoIpTypeModel *)ipType {
    if (stream) {
        //切换码流
        [self startHKPlay:index chanNum:stream.channel streamType:stream.streamType];
    }
    else if (ipType) {
        //切换内外网
        [self stopHKPlay:index];
        [self loginSDK:index];
    }
}

- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView stopOtherPlayWithSplitedStateIndex:(int)index {
    [self stopHKPlayWithNotLogoutSDK:index];
}

//选择设备
- (void)videoView:(VideoView *)view videoPlayView:(VideoPlayView *)playView splitedScreenSelectVideoWithIndex:(NSInteger)index {
    [self selectDeviceAtPictureInPictureWithIndex:(int)index];
}

- (UIView *)cancelFullScreenWithVideoView:(VideoView *)view {
    return self.view;
}

- (void)closePictureInPicture {
    [self.splitedMaskView removeFromSuperview];
    _splitedMaskView = nil;
    [self.pictureNav.view removeFromSuperview];
    [self.pictureNav removeFromParentViewController];
    self.pictureNav = nil;
}

#pragma mark - 分屏选择工区设备
- (void)selectDeviceAtPictureInPictureWithIndex:(int)index {
    
    SelectFactoryViewController *selectFactory = [SelectFactoryViewController new];
    selectFactory.style = SelectFactoryControllerStylePictureInPictureSelectDevice;
    BMWeakSelf
    [selectFactory setBlockSelectDeviceCallBack:^(SelectVideoDeviceModel *deviceModel) {
//        [weakSelf stopHKPlay:index];
        weakSelf.currentSelectIndex = (int)index;
        weakSelf.selectDeviceModel = deviceModel;
        if (deviceModel) {
            [weakSelf.deviceModelDict setObject:deviceModel forKey:@(index)];
        }
        [weakSelf processSelectDeviceCallBack:deviceModel isSplited:YES];
        [weakSelf closePictureInPicture];
    }];
    
    [selectFactory setBlockCloseNavWithPictureInPictureStyle:^{
        [weakSelf closePictureInPicture];
    }];
    
    CGRect showFrame = CGRectMake((SCREEN_WIDTH-400)*0.5, (SCREEN_HEIGHT-(SCREEN_WIDTH-40))*0.5, 400, SCREEN_WIDTH-40);
    PictureInPictureController *nav = [PictureInPictureController showInRect:showFrame rootVc:selectFactory];
    self.pictureNav = nav;
    nav.view.transform = CGAffineTransformMakeRotation(-M_PI_2);
    [[UIApplication sharedApplication].keyWindow addSubview:nav.view];
    
    [[UIApplication sharedApplication].keyWindow insertSubview:self.splitedMaskView belowSubview:nav.view];
}

#pragma mark - setter
- (void)setIsConnectedDevice:(BOOL)isConnectedDevice {
    _isConnectedDevice = isConnectedDevice;
    self.scrollView.hidden = !isConnectedDevice;
}

- (void)setSelectDeviceModel:(SelectVideoDeviceModel *)selectDeviceModel {
    _selectDeviceModel = selectDeviceModel;
    self.cameraVc.selectDeviceModel = selectDeviceModel;
}

#pragma mark - getter

- (NSMutableArray *)rateArray {
    if (!_rateArray) {
        _rateArray = [NSMutableArray array];
    }
    return _rateArray;
}

- (NSMutableDictionary *)deviceInfoDict {
    if (!_deviceInfoDict) {
        _deviceInfoDict = [NSMutableDictionary dictionary];
    }
    return _deviceInfoDict;
}

- (NSMutableDictionary *)realPlayIdDict {
    if (!_realPlayIdDict) {
        _realPlayIdDict = [NSMutableDictionary dictionary];
    }
    return _realPlayIdDict;
}

- (NSMutableDictionary *)deviceModelDict {
    if (!_deviceModelDict) {
        _deviceModelDict = [NSMutableDictionary dictionary];
    }
    return _deviceModelDict;
}

- (void)dealloc {
    if (self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [self releaseHKPlay];
//    [self stopHKPlay:0];
    [self.videoView removeFromSuperview];
    self.videoView = nil;
    thatClass = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (RKDropdownAlert *)RKAlert {
    if (!_RKAlert) {
        _RKAlert = [RKDropdownAlert alertView];
    }
    return _RKAlert;
}

- (UIView *)splitedMaskView {
    if (!_splitedMaskView) {
        _splitedMaskView = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
        _splitedMaskView.userInteractionEnabled = YES;
        [_splitedMaskView addTapGestureWithTarget:self action:@selector(clicksplitedMaskView)];
    }
    return _splitedMaskView;
}
@end
